package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class CategoryServiceImpl implements CategoryService {

    //注入mapper
    @Autowired(required = false)
    private CategoryMapper categoryMapper;
    /**
     * 新增分类
     * @param category
     * @return
     */
    @Override
    public Boolean addCategory(Category category) {
        //0.判断分类是否存在
        Category dbcategory = categoryMapper.selectCategory(category);
        if (dbcategory!=null){
            throw new BusinessException("该类别已存在，请勿重复提交~~~");
        }
        //设置创建时间和修改时间
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        return categoryMapper.addCategory(category)>0;
    }

    /**
     * 分页查询菜品分类
     *
     * @return
     */
    @Override
    public Page<Category> selectByPage(Integer page,Integer pageSize) {

        //1.设置当前页和每页大小
        PageHelper.startPage(page,pageSize);
        //2.查询所有菜品分类
        List<Category> categoryList = categoryMapper.selectAll();
        //获取分页数据
        PageInfo<Category> categoryPageInfo = new PageInfo<>(categoryList);
        //封装数据到Page
        Page<Category> categoryPage = new Page<>();
        categoryPage.setRecords(categoryPageInfo.getList());
        categoryPage.setTotal(categoryPageInfo.getTotal());


        return categoryPage;
    }

    /**
     * 删除分类
     *
     * @param id
     * @return Boolean
     */
    @Override
    public Boolean delete(Long id) {
        return categoryMapper.delete(id)>0;
    }

    /**
     * 修改分类
     *
     * @param category
     * @return
     */
    @Override
    public Boolean update(Category category) {
        //1.查询分类是否存在
        String name = category.getName();
        //根据名字查询数据是否存在分类名
        Category OldCategory = categoryMapper.selectByName(name);
        if (OldCategory!=null&&!OldCategory.getId().equals(category.getId())){
            //分类已存在
            throw new BusinessException("该类别已存在");
        }
        //2.设置修改时间
        category.setUpdateTime(LocalDateTime.now());

        //3.调用mapper完成修改
        return categoryMapper.update(category)>0;
    }

    /**
     * 根据名字查询分类
     *
     * @param name
     * @return
     */
    @Override
    public Category selectByName(String name) {
        return categoryMapper.selectByName(name);
    }

    /**
     * 获取所有菜品分类
     *
     * @return
     */
    @Override
    public List<Category> selectByType(Integer type) {
        return categoryMapper.selectByType(type);
    }
}
